package org.example.BinaryTree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Iterative_traversal_of_binary_trees {
    public static void main(String[] args) {
        //二叉树的迭代遍历

        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode root = new TreeNode(0);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);
        root.left = node1;
        root.right = node2;
        node1.left = node3;
        node1.right = node4;
        node2.left = node5;
        node2.right = node6;
        node5.left = node7;
        for (Integer i : post(root)) {
            System.out.print(i + " ");
        }
    }

    //迭代法-前序遍历
    public static List<Integer> pre(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);
            if (node.right != null) stack.add(node.right);
            if (node.left != null) stack.add(node.left);
        }
        return list;
    }
    //迭代法-后序遍历
    public static List<Integer> last(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);
            //将放栈顺序调反
            if (node.left != null) stack.add(node.left);
            if (node.right != null) stack.add(node.right);
        }
        //将数组反转
        for (int i = 0,j=list.size()-1; i < j; i++,j--) {
            int temp = list.get(i);
            list.set(i,list.get(j));
            list.set(j,temp);
        }
        return list;
    }
    //迭代法-中序遍历
    public static List<Integer> post(TreeNode root){
        ArrayList<Integer> list = new ArrayList<>();
        if (root==null) return list;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        TreeNode cur = root.left;
        //只有cur是null且stack是空才能表明此时已经将左右子树都已经遍历完全
        while (cur!=null || !stack.isEmpty()){
            if (cur!=null){
                stack.add(cur);
                cur = cur.left;
            }else{
                cur = stack.pop();
                list.add(cur.val);
                cur = cur.right;
            }
        }
        return list;
    }
}
















































